<template>
  <view class="pagecon">
    <com-banner
      src="../../static/img/11772c8712b11598385a9c1df5f5a7e.jpg"
      :styleClass="{
        position: 'fixed',
        zIndex: 1000,
        width: '100%',
        height: '222rpx',
      }"
    ></com-banner>
    <view class="box_list_2 box_list_2-abc" v-if="topmovelist.length">
      <pageMainTitle
        title="近期主题活动"
        :isShow="false"
        style="margin-top: 222rpx"
      ></pageMainTitle>
      <view class="swiper-wrapper">
        <swiper class="swiper1" circular="true" autoplay="true" interval="3000">
          <swiper-item
            @tap="$api.handleMenus(item.url, 'abc')"
            v-for="(item, index) in topmovelist"
            :key="index"
          >
            <image :src="$api.getImgUrl(item.imageUrl)"></image>
          </swiper-item>
        </swiper>
      </view>
    </view>
    <view class="box_list_1">
      <pageMainTitle
        :style="{
          'margin-top': !topmovelist.length ? '222rpx' : 'auto',
        }"
        title="活动集市"
        sub-title="更多活动"
        @menu="$api.handleMenu('/pages/interestActivity/interestActivity?index=0')"
      ></pageMainTitle>
      <classification
        v-if="0"
        :currentTab="currentTab"
        :navList="navList"
        @click="onTabClick"
      ></classification>
      <change-swiper-current
        :list="moveList"
        title="活动集市"
        @click="getBannerClick"
      ></change-swiper-current>

      <view class="box_list">
        <view
          class="item"
          v-for="(item, index) in navList"
          :key="index"
          :data-id="item.id"
          @click="onTabClick1(item)"
        >
          <view v-if="item.isShow">
            <view><image :src="item.icon" mode="aspectFit"></image></view>
            <view
              ><text>{{ item.cate_name }}</text></view
            >
          </view>
        </view>
      </view>
    </view>
    <view class="box_list_1">
      <pageMainTitle title="服务集市" :isShow="false"></pageMainTitle>
      <view class="box_list">
        <view class="item" v-for="(item, index) in groupList" :key="index" :data-id="item.id">
          <view @tap="getGruopUrl(item.id, item.sceneName, item.sceneCode)">
            <view><image :src="item.sceneLogo" mode="aspectFit"></image></view>
            <view
              ><text>{{ item.sceneName }}</text></view
            >
          </view>
        </view>
        <view class="item" @tap="$api.handleMenu('/pages/Rightshelping/Rightshelping')">
          <view><image src="/static/img/cj_ico0.png" mode="aspectFit"></image></view>
          <view><text>更多</text></view>
        </view>
      </view>
    </view>
    <view class="box_list_1">
      <pageMainTitle
        title="阵地集市"
        sub-title="地图检索"
        @menu="$api.handleMenu('/pages/frontList/frontList')"
      ></pageMainTitle>
      <change-swiper-current
        :list="groupBannerList"
        title="阵地集市"
        :isShow="false"
        @click="onBannerClick"
      ></change-swiper-current>
      <wantToDedicateCompoentns
        :list="iconPostList"
        @click="onIconPostList"
      ></wantToDedicateCompoentns>
    </view>
    <view class="box_list_1">
      <pageMainTitle title="你呼我应" :isShow="false"></pageMainTitle>
      <component-help />
    </view>
    <view class="box_list_1 tab-botton">
      <pageMainTitle
        title="风采展示"
        sub-title="更多风采"
        @menu="
          $api.handleMenu(
            `/pages/ElegantDemeanour/ElegantDemeanour?code=${elegantIndex}&state=${elegantList[elegantTab].newsType}`
          )
        "
      ></pageMainTitle>
      <classification
        :currentTab="elegantTab"
        :navList="elegantList"
        @click="onTabelegantTabClick"
        :showBar="true"
      ></classification>
      <view class="classVideoListPage-content">
        <view>
          <view>
            <view
              class="classVideo-item"
              v-for="(item, index) in topnewsList"
              :key="index"
              @tap="$api.handleMenu('/pages/newsDetail/newsDetail?id=' + item.id)"
              :data-id="item.id"
            >
              <view class="class_news_box">
                <view class="new_con">{{ item.newsTitle }}</view>
                <view class="new_img">
                  <image class="_img" :src="item.imageUrl" mode="aspectFill"></image>
                </view>
              </view>
              <view class="class_news_box_b">
                <view class="news_date">{{ item.newsOrg }} {{ item.publishTime }} </view>
                <view class="news_zf"
                  ><image class="dzimg" src="/static/img/ready-icon.png"></image>
                  {{ item.readTimes }}</view
                >
                <view class="news_dz"
                  ><image class="dzimg" src="/static/img/dz.png"></image> {{ item.dzTimes }}</view
                >
              </view>
            </view>
          </view>
        </view>

        <view>
          <view
            class="classVideo-item"
            v-for="(item, index) in newsList"
            :key="index"
            @tap="$api.handleMenu(`/pages/newsDetail/newsDetail?id=${item.id}`)"
            :data-id="item.id"
          >
            <view class="class_news_box">
              <view class="new_con">{{ item.newsTitle }}</view>
              <view class="new_img">
                <image class="_img" :src="item.imageUrl" mode="aspectFill"></image>
              </view>
            </view>
            <view class="class_news_box_b">
              <view class="news_date">{{ item.newsOrg }} {{ item.publishTime }} </view>
              <view class="news_zf"
                ><image class="dzimg" src="/static/img/ready-icon.png"></image>
                {{ item.readTimes }}</view
              >
              <view class="news_dz"
                ><image class="dzimg" src="/static/img/dz.png"></image> {{ item.dzTimes }}</view
              >
            </view>
          </view>
        </view>
        <u-empty v-if="!topnewsList.length && !newsList.length" mode="list"></u-empty>
      </view>
    </view>
    <u-popup closeable close-icon-color="#fff" border-radius="14" width="90%" height="80%"  v-model="updateShow" mode="center"
    @close="onUpdateClose"
    >
      <scroll-view scroll-y="true" style="height: auto;" class="views-data">
<!--      <view>1、新增首页编辑功能：用户可在“我的”→首页分类编辑进行首页排序调整</view>-->
<!--      <view>2、新增关注区域、关注群团共功能：用户可在“我的”里分别进行筛选关注， 系统将优先推送已关注的地区和群团的相关信息</view>-->
<!--      <view>3、新增法人登录：单位建群成功后，联系人可作为法人登录，增减单位员工</view>-->
        <view class="announcement"></view>
      </scroll-view>

      <view class="pop-close" @click="onUpdateClose">
        点击空白处关闭
      </view>
    </u-popup>
    <tabs-box></tabs-box>
  </view>
</template>

<script>
import {gdMapKey as MapKey} from '@/common/variable'
import changeSwiperCurrent from '@/components/changeSwiperCurrent/changeSwiperCurrent'
import classifications from '@/components/classifications'
import classification from '@/components/classification'
import wantToDedicateCompoentns from './compoentns/wantToDedicate/wantToDedicate'
import pageMainTitle from './compoentns/pageMainTitle/pageMainTitle'
import componentHelp from './compoentns/help'
import comBanner from './compoentns/banner'
import { gpNewsBannerList } from '@/api/banner'
import {
  gpVNewsList,
  gpSceneList,
  getGroupUrl,
  postDayVisits,
  postDayVisitsUrl
} from '@/api/news'
import {onWebviewH5} from '@/common/util'
import { appVisit } from '@/api/app'
import { DatetimeToShortTime, dateFormat } from '@/common/functions.js'
import { getGroupsCategoryList, createTime_begin, agetGroupUrls,getGroupUrlCb,onRouterLinkClick } from '@/common/type'
import { type1 } from '@/mixins/type-1'
import { news1 } from '@/mixins/news-1'
import {getMoveTypeRefresh,gpMoveTypeList} from '@/api/home-type'
export default {
  mixins: [type1, news1],
  data() {
    return {
      updateShow:false,//更新提示
      iconPostList: [], //阵地列表数据
      currentTab: 0, //活动导航第几项
      topmovelist: [], //活动展示置顶列表
      newsList: [], //风采展示列表
      topnewsList: [], //风采展示置顶列表
      groupList: [], //服务集市列表
      groupBannerList: [], //阵地轮播
      moveList: [], //活动展示列表
      frontAreaCode: '',
    }
  },
  computed: {},
  components: {
    changeSwiperCurrent,
    classification,
    wantToDedicateCompoentns,
    pageMainTitle,
    classifications,
    componentHelp,
    comBanner,
  },
  onLoad(options) {
    this.init(options)
  },
  async created() {
    this.createdMap()
  },
  onShow() {
    // #ifdef H5
    console.log('分享')
    this.$wxSetShare()
    // #endif
    this.getMoveTypeRefresh()
    this.isTokenRemind()
  },
  methods: {
    //创建地图数据
    async createdMap(){
      // #ifdef  H5
      function remoteLoad(url, hasCallback) {
        return createScript(url)
        /**
         * 创建script
         * @param url
         * @returns {Promise}
         */
        function createScript(url) {
          const scriptElement = document.createElement('script')
          document.body.appendChild(scriptElement)
          const promise = new Promise((resolve, reject) => {
            scriptElement.addEventListener(
                'load',
                (e) => {
                  removeScript(scriptElement)
                  if (!hasCallback) {
                    resolve(e)
                  }
                },
                false
            )

            scriptElement.addEventListener(
                'error',
                (e) => {
                  removeScript(scriptElement)
                  reject(e)
                },
                false
            )

            if (hasCallback) {
              window.____callback____ = function () {
                resolve()
                window.____callback____ = null
              }
            }
          })

          if (hasCallback) {
            url += '&callback=____callback____'
          }

          scriptElement.src = url

          return promise
        }

        /**
         * 移除script标签
         * @param scriptElement script dom
         */
        function removeScript(scriptElement) {
          document.body.removeChild(scriptElement)
        }
      }
      // 已载入高德地图API，则直接初始化地图
      const params = { frontAreaCode: this.frontAreaCode, frontPublic: 1 }
      if (window.AMap && window.AMapUI) {
        this.getGeolocation()
      } else {
        await remoteLoad(
            `https://webapi.amap.com/maps?v=1.4.4&key=${MapKey}&plugin=AMap.Geocoder,AMap.PlaceSearch,AMap.ToolBar`
        )
        await remoteLoad('https://webapi.amap.com/ui/1.0/main.js')
        this.getGeolocation()
      }
      // #endif
    },
    //初始化
    init(opt) {
      this.postDayVisitsUrl(opt)
      this.getBannerList(1)
      this.getBannerList(2)
      this.getBannerList(3)
      appVisit(2)
    },
    //关闭弹窗
    onUpdateClose(){
      uni.setStorageSync("update-close-next",-20001)
      this.updateShow=false

    },
    //活动集市
    resultInterestActivityList(result){
      const list = getGroupsCategoryList(result)
      let ls = []
      const abcList = list[0].navList.slice(0, 8);
      abcList.map(item=>{
        ls.push({
          cate_name:item.name,
          icon:this.$imageUrl+item.icon,
          isShow:true,
          url:item.url,
          types:'type-activity'
        })
      })
      this.navList = ls
    },
    //风采展示
    resultNewsDictItemstList(result){
      const list = getGroupsCategoryList(result)
      let ls = []

      if(list[3].navList.length){
        list[3].navList.map(item=>{
          ls.push({
            cate_name:item.name,
            newsType:item.cid,
            type:item.cid,
            code:item.code,
            types:-1
          })
        })
        this.elegantList = ls
        this.getNewsList(this.elegantList[ this.elegantTab].newsType )
      }
    },
    //服务集市
    resultGroupList(result){
      const list = getGroupsCategoryList(result)
      let ls = []
      if(list[1].navList.length){
        const glist2 = list[1].navList.slice(0,7)
        glist2.map(item=>{
          ls.push({
            id: item.cid,
            sceneCode: item.code,
            sceneLogo: this.$imageUrl+item.icon,
            sceneName: item.name
          })
        })
        this.groupList = ls
      } else {
        this.getSceneList()
      }
    },
    //阵地集市
    resultNavListList2(result){
      const list = getGroupsCategoryList(result)
      if(list[2].navList.length){
        let obj = {}
        obj['isTitleShow']=false
        obj['title']=''
        obj['list'] =[]
        obj['type2']= 'news-type2' //如果有这个，说明是自定义的
        list[2].navList.map(item=>{
          obj['list'].push({
            code:item.code,
            img: `${this.$imageUrl}${item.icon}`,
            title: item.name,
            url:item.url,
            show: true,
          })
        })
        this.iconPostList = [obj]
      }
    },
    //首页分类-分页列表查询不用登录
    gpMoveTypeList(){
      gpMoveTypeList({pageSize:999}).then((res) =>{
        const {result:{records:result}} = res
        this.resultNavListList2(result)
        this.resultGroupList(result)
        this.resultNewsDictItemstList(result)
        this.resultInterestActivityList(result)
      })
    },
    //首页分类-获取要登录
    getMoveTypeRefresh(){
      const token = uni.getStorageSync('token')
      if (token) {
        getMoveTypeRefresh().then(res=>{
          const {code,result} = res
          if(result.length || result!=='' || result.length>0){
            this.resultNavListList2(result)
            this.resultGroupList(result)
            this.resultNewsDictItemstList(result)
            this.resultInterestActivityList(result)
          }  else {
            this.gpMoveTypeList()
          }

        })
      } else {
       this.gpMoveTypeList()
      }

    },
    isTokenRemind() {
      //判断token是否存在
      const token = uni.getStorageSync('token')
      if (token) {
        this.isTokenRemindValue()
        const closeNext = uni.getStorageSync('update-close-next');
        if(!closeNext){
          this.updateShow=true
        }

      }
    },
    //提示当前时间是否已过缓存时间
    isTokenRemindValue() {
      const value = uni.getStorageSync('onremindValue')
      if (value) {
        const values = uni.getStorageSync('onremind')
        const start = this.$moment().format('yyyy-MM-dd HH:mm:ss')
        const endt = values.startTime
        if (!this.$moment(start).isAfter(endt)) {
          return
        }
        this.$api.paramsShowmodal({
          content: '是否要进入直播页面?',
          success: ({ confirm, cancel }) => {
            if (confirm) {
              onRouterLinkClick(values.moveUrl)
            } else if (cancel) {
              this.$api.msg('请点击直播页面后进入')
            }
          },
        })
      }
    },
    //用户访问量-添加访问量
    postDayVisitsUrl(options) {
      postDayVisitsUrl('pages/index/index', '群团集市')
      options.tag=options.tag || '1'
      if (options.tag) {
        uni.setStorage({ key: 'tag', data: options.tag })
        const strToday = uni.getStorageSync('today')
        const strNow = dateFormat(new Date(), 'yyyy-MM-dd')
        if (strToday == null || strToday != strNow) {
          uni.setStorageSync('today', strNow)
          postDayVisits(options.tag, 0)
        } else {
          postDayVisits(options.tag, 1)
        }
      }
    },
    //跳轮播详情
    getBannerClick(item) {
      const { url } = item
      if (url.includes('http')  || url.includes('https')) {
        if(url.includes(window.location.href)){
          this.$api.handleMenu(`${url.split('#')[1]}&values=1`)
        } else {
          return onWebviewH5(url)
        }

      } else {
        this.$api.handleMenu(`${url}&values=1`)
      }
    },
    //阵地轮播跳转
    onBannerClick(item, index) {
      if( item.title==='党群服务中心'){
        getGroupUrlCb(getGroupUrl,'1397465850763579393')
      }
      else if(item.url){
        this.$api.handleMenu(item.url)
      }

    },
    //跳转阵地
    onBannerLink(a) {
      console.log ( a )
      const url = a.good
        ? `${a.url}?title=${a.title}&value=${a.value || ''}&type=${a.type}&good=${a.good}`
        : `${a.url}?title=${a.title}&value=${a.value || ''}&type=${a.type}`
      uni.navigateTo({
        url,
      })
    },
    onTabClick1(item) {
      if(item.types==="type-activity"){
        uni.navigateTo({
          url: item.url
        })
      } else {
        uni.navigateTo({
          url: `/pages/interestActivity/interestActivity?type=${item.type}`,
        })
      }

    },
    //活动点击分类
    onTabClick(e) {
      this.currentTab = e
      const n = this.navList.findIndex((item) => {
        return item.moveType === '19'
      })
      const { cate_name, isShow, moveType, type } = this.navList[e]
      uni.navigateTo({
        url:
          type !== '19'
            ? `/pages/interestActivity/interestActivity?type=${type}

        `
            : '/pages/westlakePioneer/westlakePioneer',
      })
    },
    //阵地相关页面
    onIconPostList(item, a, index) {
      if( item.type2==='news-type2'){
        if( a.code==='301'){
          getGroupUrlCb(getGroupUrl,'1397465850763579393')
          return
        }
        const url = item.list[index].url
        if(url.includes('http') || (url.includes('https'))){
          this.$api.handleMenu(`/pages/webview/webview?url=${url}`)
        } else {
          this.$api.handleMenu(a.url)
        }
      } else {
        this.onBannerLink(a)
      }

    },
    //首页广告轮播和阵地图片轮播
    getBannerList(type = 1) {
      gpNewsBannerList({ type, isPublic: 'Y' })
        .then((res) => {
          const {
            result: { records: list },
            code,
          } = res
          if (code === 200) {
            const p = []
            list.map((item) => {
              const { imageUrl, title } = item
              p.push({
                imgurl: this.$api.getImgUrl(imageUrl),
                title,
                ...item,
              })
            })
            if (type === 1) {
              this.topmovelist = p
            } else if (type === 2) {
              this.moveList = p
            } else if (type === 3) {
              this.groupBannerList = p
            }
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    //风采展示列表
    getNewsListData(params) {
      this.newsList = []
      this.topnewsList = []
      gpVNewsList(params).then((res) => {
        if (res.success) {
          const list = []

          res.result.records.forEach((ele) => {
            const n = {
              id: ele.id,
              newsOrg: ele.newsOrg,
              imageUrl: this.$api.getImgUrl(ele.imageUrl),
              newsTitle: ele.newsTitle,
              publishTime: DatetimeToShortTime(ele.publishTime),
              readTimes: ele.readTimes,
              dzTimes: ele.dzTimes,
            }
            list.push(n)
          })
          if (params.pageSize == 3) {
            this.newsList = list
          } else if (params.pageSize == 1) {
            this.topnewsList = list
          }
        }
      })
    },
    //风采展示前3条数据
    getNewsList(newsType) {
      let params = {
        pageNo: 1,
        pageSize: 3,
        isPublish: 1,
        isTop: '2',
        order: 'desc',
      }
      //数据，判断是否与newsType相同
      const newsObject = {
        type1: ['0',''],
        type2: ['2'],
        type3: ['1', '6', '8', '9', '10'],
      }
      if (newsObject.type1.includes(newsType)) {
        params = {
          ...params,
          column: 'read_times',
          createTime_begin: createTime_begin(),
        }
      } else if (newsObject.type2.includes(newsType)) {
        params = { ...params, column: 'publish_time' }
      } else if (newsObject.type3.includes(newsType)) {
        params = { ...params, column: 'publish_time', newsType }
      }
      this.getNewsListData(params)
    },
    //定位
    getGeolocation() {
      const AMapUI = (this.AMapUI = window.AMapUI)
      const AMap = (this.AMap = window.AMap)
      const that = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        })

        geolocation.getCurrentPosition()
        if (that.frontAreaCode == undefined || that.frontAreaCode == '') {
          AMap.event.addListener(geolocation, 'complete', onComplete)
        }
        function onComplete(data) {
          var x = data.position.lng
          var y = data.position.lat
          uni.setStorageSync('lng', x)
          uni.setStorageSync('lat', y)
        }
      })
    },
    //服务集市列表
    getSceneList() {
      const params = {
        sceneHidden: '2',
        sceneHomeshow: '2',
        pageNo: 1,
        pageSize: 7,
        column: 'scene_seq',
        order: 'desc',
      }
      gpSceneList(params).then((res) => {
        if (res.success) {
          const list = []
          res.result.records.forEach((ele) => {
            list.push({
              id: ele.id,
              sceneName: ele.sceneName,
              sceneLogo: this.$imageUrl + ele.sceneLogo,
              sceneCode: ele.sceneCode,
            })
          })
          this.groupList = list
        }
      })
    },
    //阵地集市
    getGruopUrl(id, sceneName, sceneCode) {
      this.$clickGpScenePv(sceneCode)
      return agetGroupUrls(getGroupUrl, id, sceneName)
    }
  },
}
</script>

<style lang="scss">
@import"./home"
</style>
